﻿using KwaiXiaoDian.Entity.Common;
using KwaiXiaoDian.Entity.DO;
using KwaiXiaoDian.Entity.VO.GroupLeader;
using KwaiXiaoDian.IDao;
using KwaiXiaoDian.IService;
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections.Generic;
using SSharing.Frameworks.NetCore.Common.Extends;
using Microsoft.Extensions.Logging;
using System.Text;
using SSharing.Frameworks.NetCore.Common.Results;
using SSharing.Frameworks.NetCore.Common.Consts;
using Microsoft.Extensions.Configuration;
using System.Diagnostics;

namespace KwaiXiaoDian.Service
{
    /// <summary>
    /// 团长service
    /// </summary>
    public class GroupLeaderService : BaseService<TGroupLeader>, IGroupLeaderService
    {
        private readonly IGroupLeaderDao _groupLeaderDao;
        private readonly IKwaiXiaoDianService _kwaiXiaoDianService;
        private readonly ILogger<GroupLeaderService> _logger;
        private readonly IConfiguration _configuration;

        public GroupLeaderService(IGroupLeaderDao groupLeaderDao
            , IKwaiXiaoDianService kwaiXiaoDianService
            , ILogger<GroupLeaderService> logger
            , IConfiguration configuration) : base(groupLeaderDao)
        {
            _groupLeaderDao = groupLeaderDao;
            _kwaiXiaoDianService = kwaiXiaoDianService;
            _logger = logger;
            _configuration = configuration;
        }

        /// <summary>
        /// 同步团长信息
        /// </summary>
        /// <returns></returns>
        public bool Sync()
        {
            bool syncSuccess = false;
            var now = DateTime.Now;
            StringBuilder sbLog = new StringBuilder("开始同步团长信息，");
            Stopwatch stopwatch = Stopwatch.StartNew();

            //从本地获取待同步的团长列表
            var groupLeaders = _groupLeaderDao.Get(p => p.IsEnabled == Enums.IsEnabledType.Y.ToString()).ToList();
            if (!groupLeaders.HasValue())
            {
                sbLog.AppendFormat("无团长！");
                _logger.LogInformation(sbLog.ToString());

                return syncSuccess;
            }
            sbLog.AppendFormat("共：{0}个团长，", groupLeaders.Count);

            //调用快小店api获取团长信息
            foreach (var groupLeader in groupLeaders)
            {
                try
                {
                    //依据团长id获取团长信息
                    var leaderId = groupLeader.LeaderId;
                    var groupLeaderInfos = _kwaiXiaoDianService.GetGroupLeaderInfo(new GetGroupLeaderInfoRequest { Id = leaderId });
                    var groupLeaderInfo = groupLeaderInfos.FirstOrDefault();
                    if (groupLeaderInfo == null)
                    {
                        continue;
                    }

                    //更新字段
                    groupLeader.LastUpdatedBy = -1;
                    groupLeader.LastUpdatedTime = now;
                    groupLeader.Name = groupLeaderInfo.Name;
                    groupLeader.IconUrl = groupLeaderInfo.IconUrl;
                    groupLeader.Channel = groupLeaderInfo.Channel;
                    groupLeader.ProductCountThirtyDays = groupLeaderInfo.ProductCountThirtyDays;
                    groupLeader.PromoterCountThirtyDays = groupLeaderInfo.PromoterCountThirtyDays;
                    groupLeader.AvgCommissionRateThirtyDays = groupLeaderInfo.AvgCommissionRateThirtyDays;
                    groupLeader.ProductAvgpriceThirtyDays = groupLeaderInfo.ProductAvgpriceThirtyDays;
                    groupLeader.ProductCount = groupLeaderInfo.ProductCount;

                    //更新本地团长信息并持久化
                    _groupLeaderDao.Update(groupLeader);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, string.Format("同步团长信息时发生异常，团长id：{0}，团长名称：{1}，message:{0}", groupLeader.LeaderId, groupLeader.Name, ex.Message));
                }
            }
            stopwatch.Stop();
            sbLog.AppendFormat("全部同步完成，共耗时：{0}秒！", stopwatch.ElapsedMilliseconds / 1000);
            _logger.LogInformation(sbLog.ToString());

            syncSuccess = true;
            return syncSuccess;
        }

        /// <summary>
        /// 新增团长
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Tuple<bool, string> Add(AddLeaderRequest request, long userId)
        {
            //先检查该团长信息是否已存在，不存在则新增
            var addSuccess = false;
            var errorMessage = string.Empty;
            var now = DateTime.Now;

            //读取配置
            var maxLeaderCount = _configuration["MaxLeaderCount"].ToInt(30);
            var groupLeaders = _groupLeaderDao.Get(p => p.IsEnabled == Enums.IsEnabledType.Y.ToString()).ToList();
            if (groupLeaders.Count >= maxLeaderCount)
            {
                errorMessage = string.Format("团长数量已达上限（{0}个），请联系管理员！", maxLeaderCount);
                return new Tuple<bool, string>(addSuccess, errorMessage);
            }
            var groupLeader = _groupLeaderDao.Get(p => p.IsEnabled == Enums.IsEnabledType.Y.ToString() && p.LeaderId == request.LeaderId).FirstOrDefault();
            if (groupLeader != null)
            {
                errorMessage = "该团长已存在！";
                return new Tuple<bool, string>(addSuccess, errorMessage);
            }

            //新增团长
            addSuccess = _groupLeaderDao.Add(new TGroupLeader
            {
                CreatedBy = userId,
                CreatedTime = now,
                LastUpdatedBy = userId,
                LastUpdatedTime = now,
                IsEnabled = Enums.IsEnabledType.Y.ToString(),
                LeaderId = request.LeaderId,
                Name = request.LeaderName,
                IconUrl = request.IconUrl
            });

            return new Tuple<bool, string>(addSuccess, errorMessage);
        }

        /// <summary>
        /// 禁用团长
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Tuple<bool, string> Disable(DisableLeaderRequest request, long userId)
        {
            //找到指定的团长，然后修改团长的IsEnabled字段为N
            var disableSuccess = false;
            var errorMessage = "";
            var now = DateTime.Now;

            //var groupLeader = _groupLeaderDao.Get(p => p.IsEnabled == Enums.IsEnabledType.Y.ToString() && p.Id == id).FirstOrDefault();
            //if (groupLeader == null)
            //{
            //    errorMessage = "团长不存在！";
            //    return new Tuple<bool, string>(disableSuccess, errorMessage);
            //}

            ////更新团长状态
            //groupLeader.IsEnabled = Enums.IsEnabledType.N.ToString();
            //groupLeader.LastUpdatedBy = userId;
            //groupLeader.LastUpdatedTime = now;
            //disableSuccess = _groupLeaderDao.Update(groupLeader);

            var leader = _groupLeaderDao.Get(p => p.Id == request.Id).FirstOrDefault();
            if (leader == null)
            {
                errorMessage = "团长不存在!";
                return new Tuple<bool, string>(disableSuccess, errorMessage);
            }

            leader.LastUpdatedBy = userId;
            leader.LastUpdatedTime = now;
            leader.IsEnabled = request.IsEnabled;
            disableSuccess = _groupLeaderDao.Update(leader);

            return new Tuple<bool, string>(disableSuccess, errorMessage);
        }

        /// <summary>
        /// 获取团长列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public IPagingResult<Leader> GetPagingLeaders(GetPagingLeadersRequest request)
        {
            List<Leader> list = new List<Leader>();
            var pagingLeaders = _groupLeaderDao.GetPagingLeaders(request);
            if (pagingLeaders == null || !pagingLeaders.Entities.HasValue())
            {
                return new PagingResult<Leader>(pagingLeaders.TotalCount, request.Page, request.Limit, list);
            }

            foreach (var item in pagingLeaders.Entities)
            {
                var avgCommissionRateThirtyDays = "";
                var productAvgPriceThirtyDays = "";

                //平均佣金率（30日）
                if (item.AvgCommissionRateThirtyDays.HasValue)
                {
                    avgCommissionRateThirtyDays = item.AvgCommissionRateThirtyDays.Value.ToString("P2");
                }

                //商品均价（30日）
                if (item.ProductAvgpriceThirtyDays.HasValue)
                {
                    productAvgPriceThirtyDays = item.ProductAvgpriceThirtyDays.Value.ToString("F2");
                }

                list.Add(new Leader
                {
                    Id = item.Id,
                    CreatedTime = item.CreatedTime.ToString(DateTimeTypeConst.DATETIME),
                    LeaderId = item.LeaderId,
                    Name = item.Name,
                    ImageUrl = item.IconUrl,
                    Channel = item.Channel,
                    ProductCountThirtyDays = item.ProductCountThirtyDays.HasValue ? item.ProductCountThirtyDays.Value : 0,
                    PromoterCountThirtyDays = item.PromoterCountThirtyDays.HasValue ? item.PromoterCountThirtyDays.Value : 0,
                    AvgCommissionRateThirtyDays = avgCommissionRateThirtyDays,
                    ProductAvgPriceThirtyDays = productAvgPriceThirtyDays,
                    ProductCount = item.ProductCount.HasValue ? item.ProductCount.Value : 0,
                    IsEnabled = item.IsEnabled
                });
            }

            return new PagingResult<Leader>(pagingLeaders.TotalCount, request.Page, request.Limit, list);
        }


    }
}
